<template>
  <div class="home">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="车牌号" prop="carCode">
        <el-input v-model="queryParams.carCode" placeholder="请输入车牌号" clearable size="small" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-card>
      <div>
        <el-button type="success" size="small" @click="openunitDialog">新增车辆</el-button>
        <el-button type="primary" size="small" @click="refresh">刷新</el-button>
      </div>

      <el-table :data="tableData" border style="width: 100%" class="elTable">
        <el-table-column type="index" label="序号" width="100" align="center" />
        <!-- <el-table-column prop="companyCode" label="单位编号" align="center" /> -->
        <el-table-column prop="companyName" label="单位名称" align="center" />
        <!-- <el-table-column prop="carCode" label="车辆编码" align="center" /> -->
        <el-table-column prop="carNumber" label="车牌号" align="center" />
        <el-table-column prop="carType" label="车辆类别" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.carType == 'A'"> 大型车</span>
            <span v-if="scope.row.carType == 'B'"> 小型车</span>
            <span v-if="scope.row.carType == 'C'"> 小轿车</span>
          </template>
        </el-table-column>
        <el-table-column prop="brand" label="车辆品牌" align="center" />
        <el-table-column prop="model" label="车辆型号" align="center" />
        <el-table-column prop="siteNo" label="底盘号" align="center" />
        <el-table-column prop="engineNo" label="发动机号" align="center" />
        <el-table-column prop="buyDay" label="购车日期" align="center">
          <template slot-scope="scope">
            {{ scope.row.buyDay | datefmt('YYYY-MM-DD') }}
          </template>
        </el-table-column>

        <el-table-column prop="certificateNo" label="合格证号" align="center" />
        <el-table-column prop="mileage" label="里程数" align="center" />
        <el-table-column prop="quantity" label="汽油容量" align="center" />
        <!-- <el-table-column prop="oilQuantity" label="当前油量" align="center" /> -->
        <el-table-column prop="status" label="使用状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 'Y'"> 可使用</span>
            <span v-if="scope.row.status == 'U'"> 使用中</span>
            <span v-if="scope.row.status == 'P'"> 申请中</span>
            <span v-if="scope.row.status == 'W'"> 维修中</span>
          </template>
        </el-table-column>
        <el-table-column prop="isUse" label="使用状态" align="center">
          <template slot-scope="scope">
            {{ scope.row.isUse == 'Y' ? '启用' : '禁用' }}
          </template>
        </el-table-column>

        <!-- <el-table-column prop="photos" label="车辆照片" align="center" width="200">
          <template slot-scope="scope">
            <img :src="scope.row.photos" alt="" style="width: 100px" />
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button type="info" size="small" @click="editUnit(scope.row)">修改</el-button>
            <el-button type="success" size="small" @click="editCar(scope.row)">绑定司机</el-button>
            <el-button type="danger" size="small" @click="delunit(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="pageIndex" :limit.sync="pageSize" @pagination="getList" />
    </el-card>

    <el-dialog v-draggable :title="dialogTitle" :visible.sync="dialogVisible" width="80%" :modal="false">
      <el-form ref="form" :model="carDate" :rules="rules">
        <el-form-item label="车牌号" prop="carNumber">
          <el-input v-model="carDate.carNumber" />
        </el-form-item>
        <el-form-item label="车辆类别" prop="carType">
          <el-radio-group v-model="carDate.carType">
            <el-radio label="A">大型车</el-radio>
            <el-radio label="B">小型车</el-radio>
            <el-radio label="C">小轿车</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车辆品牌" prop="brand">
          <el-input v-model="carDate.brand" />
        </el-form-item>
        <el-form-item label="车辆型号" prop="model">
          <el-input v-model="carDate.model" />
        </el-form-item>
        <el-form-item label="底盘号" prop="siteNo">
          <el-input v-model="carDate.siteNo" />
        </el-form-item>
        <el-form-item label="发动机号" prop="engineNo">
          <el-input v-model="carDate.engineNo" />
        </el-form-item>
        <el-form-item label="购车日期" prop="buyDay">
          <el-date-picker v-model="carDate.buyDay" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="合格证号" prop="certificateNo">
          <el-input v-model="carDate.certificateNo" />
        </el-form-item>
        <el-form-item label="入库里程数" prop="mileage">
          <el-input v-model="carDate.mileage" />
        </el-form-item>
        <!-- <el-form-item label="车辆司机" prop="mileage">
          <el-select v-model="carDate.userCode" placeholder="请选择" style="margin-bottom: 20px">
            <el-option v-for="item in personList" :key="item.userCode" :label="item.userName" :value="item.userCode"> </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="车辆照片" prop="photos">
          <!-- <el-input v-model="carDate.photos" /> -->
          <el-upload class="photos" :action="$uploadUrl + '/uploadManager/upload'" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <div class="photos">
              <div v-for="(item, index) in carDate.photos" :key="index" class="photos">
                <img :key="index" :src="item" class="avatar" alt="avatar" />
                <el-button type="text" @click="delPhoto(index)">删除</el-button>
              </div>
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="汽油容量" prop="quantity">
          <el-input v-model="carDate.quantity" />
        </el-form-item>
        <!-- <el-form-item label="当前油量" prop="oilQuantity">
          <el-input v-model="carDate.oilQuantity" />
        </el-form-item> -->
        <el-form-item label="使用状态" prop="isUse">
          <el-radio-group v-model="carDate.isUse">
            <el-radio label="Y">启用</el-radio>
            <el-radio label="N">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addunit">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 绑定司机 -->
    <el-dialog v-draggable :title="dialogTitle" :visible.sync="dialogVisibleCar" width="50%" :modal="false">
      <el-checkbox-group v-model="carCheckList" class="d-flex">
        <el-checkbox v-for="(item, index) in checkList" :key="index" :label="item.userCode">{{ item.userName
        }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleCar = false">取 消</el-button>
        <el-button type="primary" @click="setCar">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { queryCarPage, insertCar, updateCar, deleteCar, queryDriverCar, updateDriverCar } from '@/api/unit/car'
// import { queryWorkFlowPerson } from '@/api/basice/examine';
export default {
  props: {
    dept: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      pageIndex: 1,
      pageSize: 10,
      tableData: [],
      dialogVisible: false,
      dialogVisibleCar: false,
      carOptions: {},
      total: 0,
      checkList: [],
      carCheckList: [],
      carDate: {
        photos: []
      },
      dialogTitle: '',
      queryParams: {
        deptName: ''
      },
      personList: [],

      rules: {
        carNumber: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
        carType: [{ required: true, message: '请选择车辆类别', trigger: 'change' }],
        brand: [{ required: true, message: '请输入车辆品牌', trigger: 'blur' }],
        model: [{ required: true, message: '请输入车辆型号', trigger: 'blur' }],
        siteNo: [{ required: true, message: '请输入底盘号', trigger: 'blur' }],
        engineNo: [{ required: true, message: '请输入发动机号', trigger: 'blur' }],
        buyDay: [{ required: true, message: '请输入购车日期', trigger: 'blur' }],
        certificateNo: [{ required: true, message: '请输入合格证', trigger: 'blur' }],
        mileage: [{ required: true, message: '请输入里程数', trigger: 'blur' }],
        photos: [{ type: 'array', required: true, message: '请上传车辆照片', trigger: 'change' }],
        // userCode: [{ required: true, message: '请选择司机', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入汽油容量', trigger: 'blur' }],
        oilQuantity: [{ required: true, message: '请输入当前汽油容量', trigger: 'blur' }],
        isUse: [{ required: true, message: '请选择使用状态', trigger: 'change' }]
      }
    }
  },
  created () {
    this.getList()
  },
  mounted () { },
  methods: {
    delPhoto (i) {
      this.carDate.photos.splice(i, 1)
    },
    handleAvatarSuccess (res) {
      this.carDate.photos.push(res.object.url)
      console.log(this.carDate.photos)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    refresh () {
      this.$refs.queryForm.resetFields()
      this.pageIndex = 1
      this.getList()
    },
    // async getWorkFlowPerson() {
    //   const res = await queryWorkFlowPerson({ companyCode: this.dept.companyCode, userType: 4 });
    //   this.personList = res.object;
    // },
    async getList () {
      const { object } = await queryCarPage({
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        companyCode: this.dept.companyCode,
        carNumber: this.queryParams.carCode
      })
      this.tableData = object.data
      this.total = object.count
    },

    async openunitDialog () {
      this.dialogTitle = '新增车辆'
      // this.getWorkFlowPerson();
      this.carDate = {
        photos: [],
        carType: 'A',
        isUse: 'Y'
      }

      this.carDate.companyCode = this.dept.companyCode
      this.carDate.companyName = this.dept.companyName
      // this.carDate.carType =
      this.dialogVisible = true
    },
    editUnit (val) {
      this.dialogTitle = '修改车辆'
      // this.getWorkFlowPerson();
      this.carDate = JSON.parse(JSON.stringify(val))
      this.carDate.photos = this.carDate.photos.split(',')
      console.log(this.carDate.photos)

      this.carDate.buyDay = new Date(this.carDate.buyDay)
      this.dialogVisible = true
    },
    async editCar (val) {
      this.checkList = null
      this.carOptions = {
        companyCode: val.companyCode,
        carNumber: val.carNumber
      }
      this.dialogTitle = '绑定司机'
      this.carCheckList = []

      const obj = await queryDriverCar(this.carOptions)
      this.checkList = obj.object
      this.checkList.forEach((res) => {
        if (res.carNumber === 'Y') {
          this.carCheckList.push(res.userCode)
        }
      })
      console.log(val)
      setTimeout(() => {
        console.log(this.checkList, '司机列表')
        if (this.checkList.length) {
          this.dialogVisibleCar = true
        } else {
          this.$message({
            type: 'error',
            message: '暂无司机!'
          })
        }
      }, 500)
    },

    async setCar () {
      // console.log(val);
      console.log(this.carCheckList)
      this.carOptions.messages = this.carCheckList.join('&')
      const obj = await updateDriverCar(this.carOptions)
      console.log(obj)
      this.$message({
        type: 'success',
        message: '绑定成功!'
      })
      this.dialogVisibleCar = false
    },

    delunit (val) {
      this.$confirm('此操作将永久删除车辆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await deleteCar({ id: val.id })
          if (res.code === '200') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    addunit () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const obj = JSON.parse(JSON.stringify(this.carDate))
          obj.photos = obj.photos.join(',')
          if (!this.carDate.id) {
            const res = await insertCar(obj)
            if (res.code === '200') {
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: res.message
              })
            }
          } else {
            const res = await updateCar({
              id: obj.id,
              carType: obj.carType,
              brand: obj.brand,
              model: obj.model,
              siteNo: obj.siteNo,
              engineNo: obj.engineNo,
              // userCode: obj.userCode,
              buyDay: this.$moment(this.carDate.buyDay).format('YYYY-MM-DD'),
              certificateNo: obj.certificateNo,
              mileage: obj.mileage,
              photos: obj.photos,
              quantity: obj.quantity,
              oilQuantity: obj.oilQuantity,
              isUse: obj.isUse,
              carNumber: obj.carNumber
            })
            if (res.code === '200') {
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: res.message
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.photos {
  display: flex;
  align-items: center;

  img {
    border: 1px dashed rgb(182, 182, 182);
    margin-right: 10px;
    display: block;
    width: 100px;
    height: 100px;
    object-fit: contain;
  }

  .avatar-uploader-icon {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
